/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.interceptor;

import com.jfinal.aop.Aop;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jplus.admin.annotation.JplusLog;
import io.jplus.admin.model.Log;
import io.jplus.admin.service.LogService;
import io.jplus.core.exception.JplusException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.aop.MethodInvocation;

import java.lang.reflect.Method;

public class JplusLogInterceptor {

    public JplusLogInterceptor() {
        Aop.inject(this);
    }

    @RPCInject
    LogService logService;

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Long time = System.currentTimeMillis();

        Method method = methodInvocation.getMethod();
        JplusLog jplusLog = method.getAnnotation(JplusLog.class);
        if (jplusLog == null) {
            return methodInvocation.proceed();
        }

        Log log = createLog(jplusLog, method);
        try {
            //调用执行
            Object result = methodInvocation.proceed();
            log.setTime(System.currentTimeMillis() - time);
            logService.save(log);
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.setOperation(String.format("错误信息:%s", throwable.getMessage()));
            log.setTime(System.currentTimeMillis() - time);
            logService.save(log);
            throw new JplusException(throwable);
        }
    }

    private Log createLog(JplusLog jplusLog, Method method) {
        Log log = new Log();
        log.setMethod(method.getName());
        log.setOperation(jplusLog.value());

        log.setParams(method.getParameters().toString());
        String ip = SecurityUtils.getSubject().getSession().getHost();
        log.setIp(ip);
        return log;
    }

}
